package com.android.base.tools;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by Sammie on 2017-12-06.
 */

public class HttpUrlConnectionUtil {
    private static final String TAG = "HttpUtils";

    public HttpUrlConnectionUtil() {

    }

    /**
     * 以HttpURLConnection POST提交表单
     *
     * @param path   URL
     * @param params 填写的url的参数
     * @param encode 字节编码
     * @return
     */
    public static String sendPostRequest(String path, Map<String, String> params, String encode) {
        String result = "";
        StringBuffer buffer = new StringBuffer(); // 作为StringBuffer初始化的字符串
        HttpURLConnection urlConnection = null;
        try {
            if (params != null && !params.isEmpty()) {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue(), encode)).append("&");
                }
                buffer.deleteCharAt(buffer.length() - 1); // 删除掉最有一个&
            }
            Log.i(TAG, "提交的地址及参数--->>>" + String.valueOf(buffer.toString()));
            URL url = new URL(path);
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setConnectTimeout(13000);
            urlConnection.setRequestMethod("POST"); // 设置HTTP请求方式
            urlConnection.setDoInput(true);
            urlConnection.setDoOutput(true);
            // 获得上传信息的字节大小以及长度
            byte[] mydata = buffer.toString().getBytes();
            // 表示设置请求体的类型是文本类型
            urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            urlConnection.setRequestProperty("Content-Length", String.valueOf(mydata.length));

            // 获得输出流,向服务器输出数据
            OutputStream outputStream = urlConnection.getOutputStream();
            outputStream.write(mydata, 0, mydata.length);
            outputStream.flush();
            outputStream.close();
            // 获得服务器响应的结果和状态码
            int responseCode = urlConnection.getResponseCode();
            Log.i(TAG, "状态码--->>>" + String.valueOf(responseCode));
            if (responseCode == HttpURLConnection.HTTP_OK) {
                result = changeInputStream(urlConnection.getInputStream(), encode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return result;
    }

    /**
     * 以HttpURLConnection GET方式请求
     *
     * @param path   URL
     * @param params 填写的url的参数
     * @return
     */
    public static String sendGetRequest(String path, Map<String, String> params) {
        String result = "";
        StringBuffer buffer = new StringBuffer(path);
        HttpURLConnection conn = null;

        if (params != null && !params.isEmpty()) {
            buffer.append('?');
            for (Map.Entry<String, String> entry : params.entrySet()) {
                try {
                    buffer.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(), "utf-8")).append('&');
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            buffer.deleteCharAt(buffer.length() - 1);
        }
        Log.i(TAG, "提交的地址及参数--->>>" + String.valueOf(buffer.toString()));
        try {
            URL url = new URL(buffer.toString());
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setReadTimeout(13000);
            conn.setConnectTimeout(13000);
            int responseCode = conn.getResponseCode();
            Log.i(TAG, "状态码--->>>" + String.valueOf(responseCode));
            if (responseCode == HttpURLConnection.HTTP_OK) {
                result = changeInputStream(conn.getInputStream(), "utf-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
        return result;
    }

    /**
     * 将一个输入流转换成指定编码的字符串
     *
     * @param inputStream
     * @param encode
     * @return
     */
    private static String changeInputStream(InputStream inputStream, String encode) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        byte[] data = new byte[1024];
        int len = 0;
        String result = "";
        if (inputStream != null) {
            try {
                while ((len = inputStream.read(data)) != -1) {
                    outputStream.write(data, 0, len);
                }
                result = new String(outputStream.toByteArray(), encode);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
